package com.example.filemonitor.monitor.service.impl;

import com.example.filemonitor.monitor.service.IMonitorService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.HiddenFileFilter;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class FileMonitorService implements IMonitorService  {
    @Resource
    FileListener fileListener;

    @Override
    public   void monitor(String  rootDir)  {
        // 监控目录
        log.info("start to monitor:{}",rootDir);

        // 创建过滤器
        IOFileFilter directories = FileFilterUtils.and(
                FileFilterUtils.directoryFileFilter(),
                HiddenFileFilter.VISIBLE);

        //"ppt","pptx","doc","docx","xlsx","xls","pdf"
        IOFileFilter  files = FileFilterUtils.or( FileFilterUtils.suffixFileFilter(".ppt"), FileFilterUtils.suffixFileFilter(".pptx"),
                FileFilterUtils.suffixFileFilter(".doc"), FileFilterUtils.suffixFileFilter(".docx"),
                FileFilterUtils.suffixFileFilter(".xlsx"),FileFilterUtils.suffixFileFilter(".xls"),
                FileFilterUtils.suffixFileFilter(".pdf"));
        files       = FileFilterUtils.and(
                FileFilterUtils.fileFileFilter(),
                files);


        IOFileFilter filter = FileFilterUtils.or(directories, files);

        // 使用过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir), filter);

        //不使用过滤器
        //FileAlterationObserver observer = new FileAlterationObserver(new File(rootDir));
        observer.addListener(fileListener);


        // 轮询间隔 5 秒
        long interval = TimeUnit.SECONDS.toMillis(5);
        //创建文件变化监听器
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
        // 开始监控
        try {
            monitor.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
